﻿using System;
using System.ComponentModel.Composition;
using System.Reflection;
using Castle.Windsor;
using CommonServiceLocator.WindsorAdapter;
using Microsoft.Practices.ServiceLocation;
using Reactor.Configuration;
using Reactor.Contracts;
using Reactor.Environment;

namespace Reactor.Container.Windsor
{
    [Export(typeof(ICustomizeReactorInitialization))]
    public class ContainerCustomizer : ICustomizeReactorInitialization
    {
        private readonly IWindsorContainer _container;
        private IServiceLocator _serviceLocator;

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class.
        /// <remarks>Creates a <see cref="WindsorContainer"/> and passes it to the constructor 
        /// overload that accepts an <see cref="IWindsorContainer"/> implementation.</remarks>
        /// </summary>
        public ContainerCustomizer() : this(new WindsorContainer()) {}

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class.
        /// </summary>
        /// <param name="windsorContainer">The windsor container.</param>
        public ContainerCustomizer(IWindsorContainer windsorContainer)
        {
            if (windsorContainer == null) throw new ArgumentNullException("windsorContainer");

            _container = windsorContainer;
        }

        #endregion

        #region Implementation of ICustomizeReactorInitialization

        /// <summary>
        /// Gets the execution order for this initializer. The lower the value, the earlier it will 
        /// be executed in a chain of initializers.
        /// </summary>
        /// <value>The execution order.</value>
        public uint ExecutionOrder { get { return 0; } }

        /// <summary>
        /// Initializes Reactor by providing a Windsor based <seealso cref="IServiceRegistrar"/> and <seealso cref="IServiceLocator"/>.
        /// </summary>
        public void InitializeReactor()
        {
            var windsorGate = new WindsorServiceRegistrar(_container);

            // Set platform service locator
            if (_serviceLocator == null) _serviceLocator = new WindsorServiceLocator(_container);
            Context.ServiceLocator = _serviceLocator;

            windsorGate.RegisterInstance<IServiceRegistrar>(windsorGate);
        }

        #endregion
    }
}
